﻿<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <script src="../../Scripts/js/jquery-1.8.2.js" type="text/javascript"></script>
    <script src="../../Scripts/js/jquery-ui-1.9.1.custom.min.js" type="text/javascript"></script>
    <script src="../../Scripts/js/jquery-ui-1.9.1.custom.js" type="text/javascript"></script>
    <link href="../../Content/css/jquery-ui-1.9.1.custom.css" rel="stylesheet" type="text/css" />
    <link href="../../Content/css/jquery-ui-1.9.1.custom.min.css" rel="stylesheet" type="text/css" />
    <link href="../../Content/css/MyCSS.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        String.prototype.format = function (args) {
            var str = this;            
            return str.replace(String.prototype.format.regex, function (item) {
                var intVal = parseInt(item.substring(1, item.length - 1));
                var replace;
                if (intVal >= 0) {
                    replace = args[intVal];
                } else if (intVal === -1) {
                    replace = "{";
                } else if (intVal === -2) {
                    replace = "}";
                } else {
                    replace = "";
                }
                return replace;
            });
        };
        String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g");  
              
        //Load after check with session, user has signed in
        function load() {
            var text = $("#username").val();
            $("#displaylogin").text(text);            
            $("#loginFalse").hide();
            $("#loginSuccess").show();
        };

        //Ajax form to using multitime
        function SendAjax(method, urlRequest, dataSend, successFunc)
        {
         $.ajax({
                url: urlRequest.toString(),                                   
                data: dataSend,  
                dataType: "json",
                type: method.toString(),             
                success: successFunc,
                error: function (x, y, z) {
                        alert("Had error! Please, Try again!");
                        return;
                }                         
            });      
        }
       
        function getBase64Image() {
            // Create an empty canvas element
            var canvas = document.createElement("canvas");
            var img = document.getElementById('ImageRaw');                       
            canvas.width = img.width;
            canvas.height = img.height;
            // Copy the image contents to the canvas
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);            
            // Get the data-URL formatted image
            // Firefox supports PNG and JPEG. You could check img.src to
            // guess the original format, but be aware the using "image/jpg"
            // will re-encode the image.
            var dataURL = canvas.toDataURL("image/jpeg");

            return dataURL.replace("data:image/jpeg;base64,","");
        }

        function SendImage()
        {
            if($("#UserName").val() != "" && $('#Image').val() != "")
            {
                var urlRequest = 'http://localhost:49509/api/Picture/' + $("#UserName").val();   
                var dataSend = new Object();                
                dataSend.Content = getBase64Image();
                SendAjax('POST', urlRequest, dataSend, null);                             
            }
        }
        
        function GetPolling(urlRequest, dataSend, funcPoll, successFunc, timeoutPoll)
        {
           $.ajax({
            url: urlRequest,
            data: dataSend,
            complete: funcPoll,
            timeout: timeoutPoll,
            success: successFunc
            });            
        }       

        function Login(urlRequest){
            var username = $('#txtUsername').val();
            var password = $('#txtPassword').val();
            var data = new Object();
            data.Password = password;
            var successFunc =  function (result) {                                                  
                                    var url =  result.RedirectURL;                                
                                    if(url != null)
                                    {                                        
                                        url = url + "?RequestToken=" + result.Oauth_token;
                                        alert(url);
                                        window.location = url;
                                    }
                                    else
                                    {                                                                                                                            
                                        if(result == "Used")
                                        {
                                            alert("This account has loged in!");
                                            return;
                                        }
                                        else if(result == "Invalid")
                                        {
                                            alert("Username or password invalid!");
                                            return;
                                        }                                                   
                                        signin = "true";                            
                                        SendAjaxLogon(username, mod);
                                        if(result == "Valid")
                                            $("#username").val(username);
                                        else
                                            $("#username").val(result);
                                        load();
                                        GetFriend(urlRequest);
                                        if(mod   != "1")                                                                           
                                            GetMessage();                                    
                                        GetState();
                                    }
                                };
            var url = urlRequest + username;            
            SendAjax("GET",url,data,successFunc);                               
        }

        function Logout(urlRequest){
            var url = urlRequest + $("#username").val();
            var successFunc = function (result) {
                        if(result == "sc")
                        {
                            location.href='@Url.Action("Logout")';                     
                            $("#menu").html("");
                            $("#menu").menu("refresh");
                        }
                        else
                            alert("Had error cannot logout, try again!");
                        };         
            SendAjax("POST",url,null,successFunc);               
        }
   
        function ProcessMessage(index, value)
        {        
            var user = value.split(',');
            var me = "";
            var desWall = "";
            if(user[0] == $("#username").val())
            {
                me = " me";
                desWall= user[1].split('-')[1];
            }
            var strPrint = messagePrint.format([me, user[0], user[2]]);          
            if(desWall == "")     
            {
                var tag = document.getElementById(user[0]);
                if(tag == null)
                    CreateTab(user[0]);
                $("#" + user[0]).find("#chatview").append(strPrint);
               // playSound("../../Content/css/audio/alert.wav");
            }
            else
            {
                var tag = document.getElementById(desWall);
                if(tag == null)
                    CreateTab(desWall);
                $("#" + desWall).find("#chatview").append(strPrint);
            }
        }

        //Long polling get message from server
        function GetMessage(){           
            var urlRequest = 'http://localhost:49509/api/Message/' + $("#username").val();                                      
            var data = new Object();
            data.currentMesIndex = currentIndex;
            var successFunc = function(data){ 
                    if(data != null)  
                    {
                        $.each(data,function(index,value){                      
                            ProcessMessage(index, value);
                            currentIndex++;                        
                        });                             
                        if(currentIndex > 20)                                        
                            currentIndex = 0;    
                    }                
                };    
            GetPolling(urlRequest,data,GetMessage,successFunc,60000);                        
        }

        //Long polling get state change from server
         function GetState(){           
            var urlRequest = 'http://localhost:49509/api/State/' + $("#username").val();                                       
            if(mod == 1)
                urlRequest = 'http://localhost:49509/api/YahooState/' + $("#username").val();                                       
            var successFunc = function(data){ 
                    if(data != null) 
                    {
                        $.each(data,function(index,value){    
                            switch (value.Type)
                                {
                                  case 'Online': 
                                  {
                                    $("#m-" + value.Actor).toggleClass('ui-state-disabled',false);
                                    playSound("../../Content/css/audio/online.wav");
                                  }
                                    break;                        
                                  case 'Offline': 
                                  {
                                    $("#m-" + value.Actor).toggleClass('ui-state-disabled',true);
                                    playSound("../../Content/css/audio/offline.wav");
                                  }
                                    break;                             
                                  case 'Message':
                                  {
                                    ProcessMessage(index,value.Actor);
                                    playSound("../../Content/css/audio/alert.wav");
                                  }
                                    break;
                                  case 'acceptF':
                                  {
                                    GetFriend('http://localhost:49509/api/Account/');
                                  }
                                    break;
                                  case 'requestF':
                                  {
                                    $('#dialogAgree').append(requestitem.format([value.Actor]));                              
                                  }
                                    break;
                                }                      
                        }); 
                        $('#menu').menu("refresh");  
                        if($('#dialogAgree div')[0] != null)
                            $('#dialogAgree').dialog("open");
                    }
                };    
            GetPolling(urlRequest,null,GetState,successFunc,120000);                        
        }

        //Set session save user after login validate
        function SendAjaxLogon(username, mod){
             $.ajax({
                url: '@Url.Action("Logon")',                                   
                data: {id: username, Mode:mod}               
            });
        }

        //Get list friend to update menu
        function GetFriend(urlRequest){                     
            var url = urlRequest + $("#username").val();            
            var funcSuccess = function(result) {  
                        if(result != "" && result != null)             
                        {     
                          $("#menu").html("");  
                          $.each(result,function(index,value){                      
                            var state = offline;
                            if(value.State == true)
                                state = "";
                            var imgName = "http://localhost:49509/api/Picture/" + value.Username;
                                if(mod == 1)
                                {
                                    imgName = "http://img.msg.yahoo.com/avatar.php?yids=" + value.Username;
                                }
                            var str = menuitem.format([state,value.Username,imgName]);
                            $('#menu').append(str);
                          });
                          $('#menu').menu("refresh");
                        }
                    };  
            SendAjax('GET',url,null,funcSuccess);                  
        }                
             
       //Send message to server       
       function SendMessage(recipient){                      
            var txt = $("#" + recipient).find("#textinput").val();            
            if(txt != "" && txt != null)
            {                                
                var userReceive = recipient;
                var me = $("#username").val();    
                var urlRequest = 'http://localhost:49509/api/YahooAction/' + $("#username").val();
                var messSend = new Object();                                
                    messSend.Message = txt; 
                if(mod != "1")
                {
                    urlRequest = 'http://localhost:49509/api/SendMessage/' + $("#username").val();                                                      
                    messSend.UserReceive = me + '-' + userReceive;           
                    SendAjax('POST',urlRequest,messSend,null);  
                }   
                else{                
                    var strPrint = messagePrint.format([" me", me, txt]);            
                    $("#" + userReceive).find("#chatview").append(strPrint);                
                }
                messSend.UserReceive = userReceive;           
                SendAjax('POST',urlRequest,messSend,null);                 
            }                
        }      
        
        function RequestAccept(accept,recipient, ele)
        {
            if(mod == 1)
            {
                alert("Yahoo!Chat mode doesn't support this function");
                return;
            }                                                                
            var userReceive = recipient;              
            var urlRequest = 'http://localhost:49509/api/Friend/' + $("#username").val() + "?userReceive=" + userReceive+"&accept="+accept;        
            var successFunc = function(data){
                if(data != "OK")
                    alert("Had error!");
                else{
                    $('#n-' + recipient).remove();
                    GetFriend('http://localhost:49509/api/Account/');                    
                }
            };
            SendAjax('POST',urlRequest,null,successFunc);      
        }


        function Requestfriend(recipient){         
            if(mod == 1)
            {
                alert("Yahoo!Chat mode doesn't support this function");
                return;
            }                                                                
            var userReceive = recipient;              
            var urlRequest = 'http://localhost:49509/api/Friend/' + $("#username").val() + "?userReceive=" + userReceive;        
            var successFunc = function(data){
                if(data == "NotExist")
                    alert("User not exist");
                if(data == "")
                    alert("Had error for input");
                if(data == "OK")
                    $('#dialogAdd').dialog("close");
            };
            SendAjax('POST',urlRequest,null,successFunc);                             
        }                 

        function CreateTab(username)
        {            
            var tag = document.getElementById(username);
            var index = -1;
            //Not found tab
            if(tag == null)
            {
                var str = tabitemLI.format([username]);            
                $('#tabs ul').append(str);
                str = tabitemDIV.format([username,content.format([username])]);
                $('#tabs').append(str);
                $('#tabs').tabs("refresh");
                return $("#tabs li").length - 1;
                
            }
            else
            {            
                $("#tabs a").each(function(i){                                                        
                    if(username == this.text)
                        index = i;  
                });     
            }                 
            return index;              
        }
        
        function DeleteFriend(username)
        {
            /*var str = tabitemLI.format([username]);
            $('#tabs ul').append(str);
            str = tabitemDIV.format([username]);
            $('#tabs').append(str);
            $('#tabs').tabs("refresh");
            $('#tabs').tabs("option","selected", $("#tabs li").length - 1);*/
            return;
        }    
        
        function PressEnterExcuteClick(e, user, ele)                                                     
        {
            if(e)
                e = e;
            else
                e = window.event;            
            var keycode;
            if(e.which)
                keycode = e.which;
            else 
                keycode = e.keyCode;            
            var element = $("#" + ele);
            if(user != "")
                element = $("#" + user).find("#" + ele);       
            
            if(keycode == 13) {
                element.click();
                e.preventDefault();
            }            
        }

        function removeTabs(e, ele)
        {
            if(e)
                e = e;
            else
                e = window.event;            
   
            if(e.which == 2)
            {
                var panelId = $(ele).closest("li").remove().attr("aria-controls");
                $("#" + panelId).remove();
                $('#tabs').tabs("refresh");
            }
            return;
        }

        function ShowAddDialog()
        {
             if (signin == "true" && signin && mod != "1")
             {
                $('#dialogAdd').dialog("open");          
             }
        }

        function InitDialog()
        {
            $('#dialog').dialog(
            {
                autoOpen: false,
                show: "blind",
                hide: "explode",
                modal:true
            });

            $('#dialogAdd').dialog(
            {
                autoOpen: false,
                show: "blind",
                hide: "explode",
                modal:true,
                buttons: {
                    "Add friend": function() {
                        if($('#addUser').val() != "")
                            Requestfriend($('#addUser').val());
                        else alert("Input not true form!");
                    },
                    Cancel: function() {
                        $(this).dialog("close");
                    }
                },
            });

            $('#dialogAgree').dialog(
            {
                autoOpen: false,
                show: "blind",
                hide: "explode",
                modal:true,
                width: 400,
                buttons: {
                    Cancel: function() {
                        $(this).dialog("close");
                    }
                },
            });

            
        }

        function playSound(soundfile) {
            document.getElementById("dummy").innerHTML=
            "<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
        }

        var messagePrint = "<p><span class = 'username{0}'>{1}:</span>{2}</p>";
        var menuitem = "<li id='m-{1}' {0}><img src='{2}' alt='loading' style='width: 40px; height: 40px;'/><a href='#' style='position:relative; bottom: 15px; display:inline-block;'>{1}</a><ul><li><a href='#' onclick=\"var i = CreateTab('{1}'); if(i!=-1) $('#tabs').tabs('option','selected', i); return;\">Chat</a></li><li><a href='#' onclick=\"DeleteFriend('{1}'); return;\">Delete</a></li></ul></li>";
        var tabitemLI =  "<li><a href='#{0}' class='tabs' onmousedown='removeTabs(event, this)'>{0}</a><span class='ui-icon ui-icon-close'></span></li>";
        var tabitemDIV = "<div id='{0}' class='tabsub'>{1}</div>";
        var content = "<textarea id='textinput' onkeydown=\"PressEnterExcuteClick(event, '{0}' ,'btnsend');\"></textarea><input type='button' id='btnsend' value = 'Send message' onclick=\"SendMessage('{0}'); $('#{0}').find('#textinput').val('');\"/><div id = 'chatview'></div>";
        var offline = "class = 'ui-state-disabled'";   
        var requestitem = "<div id='n-{0}' style='display: inline-block'><div style='width: 180px; display: inline-block;'><label style='color: Orange;'>{0}</label></div><input type='button'  onclick=\"RequestAccept('true','{0}')\" value='Agree'/><input type='button' value='Decline' onclick=\"RequestAccept('false','{0}')\" style='margin-left: 5px'/></div>";             
        var signin = "false";
        var token = "";
        var sessionid = "";        
        var currentIndex = 0;
        var mode = "0"; //1 yahoo
     
        $(document).ready(function () {
            $('#tabs').tabs();
            $('#menu').menu();      
            InitDialog();   
            //$.support.cors = true;
            $("#loginSuccess").hide();           
            //Check logon        
            @{
                var login = HttpContext.Current.Session["login"] as string;
                var name = HttpContext.Current.Session["username"] as string;
                var mode = HttpContext.Current.Session["Mode"] as string;
                var error = HttpContext.Current.Session["Error"] as string;
            };      
            if('@error' != null && '@error' != "")
                alert(error);
            signin = '@login';            
            mod = '@mode';
            var txt = '@name';
            if(txt != "" && txt)
            {            
                $("#username").val(txt);                
            }
            if (signin == "true" && signin)
            {          
                var urlRequest = 'http://localhost:49509/api/Account/';
                if(mod == "1")
                    urlRequest = 'http://localhost:49509/api/yahoo/';
                load();     
                GetFriend(urlRequest);
                if(mod != "1")
                    GetMessage();
                GetState();
            }          
            /*$('#btnYahooLogin').click(function(){
                var urlRequest = 'http://localhost:49509/api/Yahoo/';
                Login(urlRequest); 
            });*/

            $('#btnLogin').click(function () {                
                if($("#txtUsername").val()!= "" && $("#txtPassword").val() != "")  
                {    
                    $('#dialog').dialog('open');               
                }
                else
                    alert("You must confirm Username and Password!");
            });     
            
            $('#CAtype').live("click",function(){
                mod = "0";
                $('#dialog').dialog('close');
                var urlRequest = 'http://localhost:49509/api/Account/';
                Login(urlRequest);
                $('#logo').attr("src","../../Content/css/images/ChatAjax.png");
            });   
            
             $('#YHtype').live("click",function(){
                mod = "1";
                $('#dialog').dialog('close');
                var urlRequest = 'http://localhost:49509/api/Yahoo/';
                Login(urlRequest); 
                $('#logo').attr("src","../../Content/css/images/YHChat.png");
            });  

            $('#btnLogout').click(function(){
                var urlRequest = 'http://localhost:49509/api/Account/';   
                if(mod == "1")
                    urlRequest = 'http://localhost:49509/api/Yahoo/';   
                Logout(urlRequest);           
            });

            $("#tabs span.ui-icon-close" ).live( "click", function() {
                var panelId = $(this).closest("li").remove().attr("aria-controls");
                $("#" + panelId).remove();
                tabs.tabs("refresh");
            });
        });
    </script>
</head>
<body>
    <span id="dummy" style="visibility: hidden;"></span>
    <img id="logo" src="../../Content/css/images/ChatAjax.png" onclick="ShowAddDialog()"
        style="position: absolute; top: 0px; left: 20px; width: 90px; z-index: 10; height: 70px;"
        alt="loading" />
    <p id="username" style="visibility: hidden">
    </p>
    <div id="loginPanel">
        <div id="loginFalse">
            <p style="right: 12px; top: 0px; margin-top: 0;">
                <label>
                    Username</label>
                <input type="text" id="txtUsername" style="margin-right: 10px;" />
                <input type="button" id="btnLogin" value="Login" />
            </p>
            <p style="right: 5px; top: 15px;">
                <label>
                    Password</label>
                <input type="password" id="txtPassword" />
                <input type="button" id="btnSignUp" value="Sign Up" onclick="location.href='@Url.Action("Register")' "/>
            </p>
        </div>
        <div id="loginSuccess">
            <p style="right: 12px; top: 10px; margin-top: 0;">
                <label id="displaylogin">
                    Success</label>
                <input type="button" id="btnLogout" value="Log Out" />
            </p>
        </div>
    </div>
    <div id="bodyPanel">
        @RenderBody()
    </div>
    <div id="dialog" title="What type chat do you want?" style="display: block">
        <p style="color: Blue; font-size: large; margin-top: 0px;">
            Choose your type image to login</p>
        <div style="display: inline-block">
            <label style="color: Orange; font-size: large;">
                Yahoo chat!</label>
            <label style="color: Orange; margin-left: 60px; font-size: large;">
                Chat ajax</label>
        </div>
        <div style="display: inline-block">
            <img id="YHtype" src="../../Content/css/images/YHChat.png" alt="loading" style="width: 70px;
                height: 70px; margin-top: 10px; margin-left: 5px;" />
            <img id="CAtype" src="../../Content/css/images/ChatAjax.png" alt="loading" style="width: 90px;
                height: 70px; margin-left: 80px" />
        </div>
    </div>
    <div id="dialogAdd" title="Add friend" style="display: block">
        <p style="color: Blue; font-size: large; margin-top: 0px;">
            Fill Username:</p>
        <input type="text" id="addUser" style="width: 270px;" />
    </div>
    <div id="dialogAgree" title="Friend submit" style="display: block">
        <p style="color: Blue; font-size: large; margin-top: 0px;">
            These users want to be your friend:</p>
    </div>
</body>
</html>
